package com.insight.common.message.listener;

import com.alibaba.fastjson.JSONObject;
import com.insight.common.message.websocket.WebSocket;
import com.insight.common.mq.aspect.annotation.RedisMessageExtend;
import com.insight.common.mq.stream.Streams;
import com.insight.common.mq.utils.AnalyzeContent;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.stream.StreamListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.util.Map;

/**
 * @author JinPengDong
 * @date 2023/10/13
 */
@Component
public class WebSocketSendOneEventListener implements StreamListener<String, MapRecord<String, String, String>> {
    @Override
    @Async("stream-core-pool")
    @RedisMessageExtend(stream = Streams.WEBSOCKET_CURRENT)
    public void onMessage(MapRecord<String, String, String> message) {
        final Map<String, String> value = message.getValue();
        final JSONObject content = AnalyzeContent.getContent(value);
        final String userId = content.getString("userId");
        final Map<String, Session> sessionPool = WebSocket.getSessionPool();
        Session session = sessionPool.get(userId);
        if (session != null && session.isOpen()) {
            WebSocket.sendMessage(session, content.getString("message"));
        }
    }
}
